#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include <jsoncpp/json/json.h>

// #include "oj_model.hpp"
#include "oj_model2.hpp"
#include "oj_view.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"

namespace ns_control
{
    using namespace std;
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_log;
    using namespace ns_util;
    using namespace httplib;

    class Machine
    {
    public:
        string ip;
        int port;
        uint64_t load; // 服务器负载
        mutex *mtx;    // C++封装的mutex禁止拷贝
    public:
        Machine()
            : ip(""),
              port(0),
              load(0),
              mtx(nullptr)
        {
        }

        void IncLoad()
        {
            mtx->lock();
            ++load;
            mtx->unlock();
        }
        void DecLoad()
        {
            mtx->lock();
            --load;
            mtx->unlock();
        }
        void ResetLoad()
        {
            mtx->lock();
            load = 0;
            mtx->unlock();
        }

        uint64_t Load()
        {
            uint64_t _load;
            mtx->lock();
            _load = load;
            mtx->unlock();

            return _load;
        }
    };

    const string service_machine = "./conf/server_machine.conf";

    class LoadBalance
    {
    private:
        // 所有提供编译服务的主机, 通过下标进行后续操作
        vector<Machine> machines;
        // 在线主机列表
        vector<int> online;
        // 离线主机列表
        vector<int> offline;
        // 互斥锁，保护在线和离线主机列表
        mutex mtx;

    public:
        LoadBalance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载 " << service_machine << " 成功" << endl;
        }
        bool LoadConf(const string &machine_conf)
        {
            ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载" << machine_conf << "失败" << endl;
                return false;
            }
            string line;
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SpiltString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(ERROR) << "加载主机" << line << "失败" << endl;
                    continue;
                }

                Machine m;
                m.ip = tokens[0];
                m.port = stoi(tokens[1]);
                m.load = 0;
                m.mtx = new mutex();

                online.push_back(machines.size());
                machines.push_back(m);
            }
            return true;
        }
        bool SmartChoice(int *id, Machine **m)
        {
            // 1. 使用选择好的主机(更新该主机的负载)
            // 2. 我们需要可能离线该主机
            mtx.lock();
            // 负载均衡的算法
            // 1. 随机数+hash
            // 2. 轮询+hash

            int online_num = online.size();
            if (online_num == 0)
            {
                LOG(FATAL) << "没有在线主机" << endl;
                mtx.unlock();
                return false;
            }

            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = (*m)->Load();
            for (auto curr_id : online)
            {
                uint64_t curr_load = machines[curr_id].Load();
                if (curr_load < min_load)
                {
                    min_load = curr_load;
                    *id = curr_id;
                    *m = &machines[*id];
                }
            }
            mtx.unlock();
            return true;
        }
        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].ResetLoad();
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }
        void OnlineMachine()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.clear();
            mtx.unlock();

            LOG(INFO) << "所有主机上线" << endl;
        }
        void ShowMachines()
        {
            mtx.lock();
            cout << "在线主机列表:";
            for (auto &id : online)
            {
                cout << id << ' ';
            }
            cout << endl;
            cout << "离线主机列表:";
            for (auto &id : offline)
            {
                cout << id << ' ';
            }
            cout << endl;
            mtx.unlock();
        }
    };

    class Control
    {
    private:
        Model model_;             // 提供后台数据
        View view_;               // 渲染HTML
        LoadBalance load_blance_; // 核心负载均衡器

    public:
        void RecoveryMachine()
        {
            load_blance_.OnlineMachine();
        }

        bool GetAllQuestion(string *html)
        {
            vector<ns_model::Question> all;
            if (model_.GetAllQuestion(&all))
            {
                // 获取题目信息成功，将所有的题目数据构建成网页
                view_.ExpandAllQuestion(all, html);
                return true;
            }
            else
            {
                *html = "获取题目失败, 形成题目列表失败";
                return false;
            }
        }
        bool Question(const string &number, string *html)
        {
            ns_model::Question q;
            if (model_.GetOneQuestion(number, &q))
            {
                view_.ExpandOneQuestion(q, html);
                return true;
            }
            else
            {
                *html = "所选题目" + number + "不存在";
                return false;
            }
        }
        void Judge(string number, const std::string in_json, std::string *out_json)
        {
            // 根据题目编号获取题目信息
            struct Question q;
            model_.GetOneQuestion(number, &q);

            // 反序列化json串，获得题目ID和用户代码,input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            string code = in_value["code"].asString();

            // 拼接用户代码和测试代码
            Json::Value compiler;
            compiler["input"] = in_value["input"];
            compiler["code"] = code + "\n" + q.tail;
            compiler["cpu_limit"] = q.cpu_limit;
            compiler["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            string compile_string = writer.write(compiler);

            // 选择负载最低主机
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!load_blance_.SmartChoice(&id, &m))
                    break;

                // 将HTTP编译请求发送到主机
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO) << " 选择主机成功, 主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 当前主机负载: " << m->Load() << "\n";
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 将结果赋值到out_json
                    *out_json = res->body;
                    LOG(INFO) << "编译和运行成功" << endl;
                    m->DecLoad();
                    break;
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "当前请求主机 id: " << id << " 详情: " << m->ip << " : " << m->port << " 可能离线" << endl;
                    load_blance_.OfflineMachine(id);
                    load_blance_.ShowMachines(); // 仅用于调试
                }
            }
        }
    };

}